// Copyright 2011 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.apache.tapestry.csrfprotection.demo.pages;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry.csrfprotection.demo.util.TestBean;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.csrfprotection.CsrfProtected;

/**
 * Page that displays a AjaxFormLoop component with a list of dummy values.
 */
public class AjaxFormLoop {
	@Property
	@Persist
	private List<TestBean> myList;
	
	@Property
	private TestBean _testBean;
		
	@SuppressWarnings("rawtypes")
	public ValueEncoder getEncoder() {
		return new ValueEncoder<TestBean>() {

			public String toClient(TestBean value) {
				return value.getTestProperty();
			}

			public TestBean toValue(String keyAsString) {
				return new TestBean(keyAsString);
			}
		};
	}
	
	void onActivate(){
		if(myList == null){
			myList = new ArrayList<TestBean>();
			myList.add(new TestBean("bla"));
			myList.add(new TestBean("test"));
			myList.add(new TestBean("foo"));
		}
	}
	
	@Log
	@CsrfProtected
	void onRemoveRow(TestBean bean){
		myList.remove(bean);
	}
	
	@Log
	@CsrfProtected
	TestBean onAddRow(){
		TestBean newBean = new TestBean("new");
		myList.add(newBean);
		return newBean;
	}
}
